import React, { lazy, Suspense, useEffect, useState } from 'react'
import { Space, Table, Tag, Button, message, Flex, Input, Modal, Spin, Card, Row, Col, Typography, Divider, Pagination } from 'antd'
import type { TableProps, SpinProps } from 'antd';
import { 
  FileAddOutlined, FileProtectOutlined, FolderAddOutlined, 
  SearchOutlined, UserOutlined, ZoomOutOutlined, EditOutlined, 
  DeleteOutlined, TableOutlined, BlockOutlined 
} from '@ant-design/icons'
import http from '../api/http'
import type { IUsers, IUsersWrite } from '../types/users'
import type { IGanyut } from '~/types/ganyut';
import dayjs from 'dayjs';

const { Title, Text } = Typography;
type TableRowSelection<T extends object = object> = TableProps<T>['rowSelection'];
const AddUserForm = lazy(() => import('./add'));
const AddUserForm1 = lazy(() => import('./chax'));
const { Column } = Table

const Users: React.FC = () => {
  // 布局切换状态管理
  const [layoutMode, setLayoutMode] = useState<'table' | 'card'>('table');
  // 当前页码
  const [currentPage, setCurrentPage] = useState(1);
  // 每页显示2条数据
  const constPageSize = 3;
  
  // 表格选择相关
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<IGanyut> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: '选择奇数行',
        onSelect: (changeableRowKeys) => {
          setSelectedRowKeys(changeableRowKeys.filter((_, index) => index % 2 === 0));
        },
      },
      {
        key: 'even',
        text: '选择偶数行',
        onSelect: (changeableRowKeys) => {
          setSelectedRowKeys(changeableRowKeys.filter((_, index) => index % 2 !== 0));
        },
      },
    ],
  };

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpen1, setIsModalOpen1] = useState(false);
  const [loading, setLoading] = useState<boolean | SpinProps>({ size: 'large' })
  const [count, setCount] = useState(0)
  const [data, setData] = useState<Array<IGanyut>>([])
  const [inputvalue, setvalue] = useState('');

  // 获取用户数据 - 每页2条
  const fetchUsers = async (page: number, size: number = constPageSize) => {
    const currentTime = new Date();

  // 格式化时间（示例：2025-10-22 15:30:45）
  const formattedTime = currentTime.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
    console.log(currentTime)
    setLoading({ size: 'large' })
    try {
      const response = await http.getList<IGanyut>('Ganyut', { 
        page: page, 
        size: size, 
        name: inputvalue 
      })
      console.log(response.data)
      setData(response.data)
      setCount(response.count)
      setCurrentPage(page)
    } catch (error) {
      message.error('数据加载失败')
    } finally {
      setTimeout(() => setLoading(false), 200);
    }
  }

  const changeCount1 = (event: React.ChangeEvent<HTMLInputElement>) => {
    setvalue(event.target.value);
  }

  // 初始化加载数据
  useEffect(() => {
    fetchUsers(1)
  }, [])

  // 新增按钮加载效果
  const [loadings, setLoadings] = useState<boolean[]>([]);
  const enterLoading = (index: number) => {
    setLoadings(prev => {
      const newLoadings = [...prev];
      newLoadings[index] = true;
      return newLoadings;
    });

    setTimeout(() => {
      setLoadings(prev => {
        const newLoadings = [...prev];
        newLoadings[index] = false;
        return newLoadings;
      });
      setIsModalOpen(true);
    }, 500);
  };

  // 刷新与模态框控制
  const handleCancel = () => {
    setIsModalOpen(false);
  };
    const handleCance2 = () => {
    setIsModalOpen1(false);
  };
  const handleAddSuccess = () => {
    setIsModalOpen(false);
    fetchUsers(1); // 新增成功后刷新数据
  };
    const handleAddSuccess1 = () => {
    setIsModalOpen1(false);
    fetchUsers(1); // 新增成功后刷新数据
  };

  // 查询按钮加载效果
  const [loadings1, setLoadings1] = useState<boolean[]>([]);
  const enterLoading1 = (index: number) => {
    setLoadings1(prev => {
      const newLoadings = [...prev];
      newLoadings[index] = true;
      return newLoadings;
    });

    setTimeout(() => {
      setLoadings1(prev => {
        const newLoadings = [...prev];
        newLoadings[index] = false;
        return newLoadings;
      });
      fetchUsers(1)
    }, 500);
  };
  const [pageValue, setPageValue] = useState(2);
const xian=(zz:number)=>{
 setPageValue(zz)
  setIsModalOpen1(true);
}
  // 删除操作
  const delUser = (id: number) => {
    message.success(id + "删除成功！");
    fetchUsers(currentPage); // 删除后刷新当前页
  }

  // 样式定义
  const yellowButtonStyle = {
    backgroundColor: '#faad14',
    borderColor: '#faad14',
    '&:hover': {
      backgroundColor: '#ffc53d',
      borderColor: '#ffc53d',
    },
    '&:active': {
      backgroundColor: '#d48806',
      borderColor: '#d48806',
    },
  };

  // 操作按钮统一样式
  const actionButtonStyle = {
    margin: '0 2px',
    padding: '4px 8px',
    borderRadius: 4,
    transition: 'all 0.2s'
  };

  // 卡片布局渲染函数 - 补全所有体质信息
  const renderCardLayout = () => (
    <div>
      <Spin spinning={loading}>
        <Row gutter={[24, 24]}>
          {data.map((item) => (
            <Col xs={24} sm={12} lg={8} key={item.id}>
              <Card 
                hoverable 
                bordered 
                className="transition-all duration-300 hover:shadow-lg"
                style={{ height: '100%' }}
              >
                {/* 卡片头部 */}
                <div className="mb-3">
                  <Title level={5} style={{ margin: 0, display: 'flex', justifyContent: 'space-between' }}>
                    <span>{item.name}</span>
                    <Text type="secondary" style={{ fontSize: 14 }}>{item.fileNumber}</Text>
                  </Title>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
                    <Text type="secondary" style={{ fontSize: 13 }}>
                      性别: {item.sex || '-'}
                    </Text>
                    <Text type="secondary" style={{ fontSize: 13 }}>
                      评估日期: {item.pdata ? dayjs(item.pdata).format('YYYY-MM-DD') : '-'}
                    </Text>
                  </div>
                </div>
                
                <Divider style={{ margin: '12px 0' }} />
                
                {/* 体质信息 - 补全所有项 */}
                <div className="space-y-2">
                  <div className="flex justify-between items-center">
                    <Text size="small">气虚质:</Text>
                    {item.qi === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">平和质:</Text>
                    {item.pin == 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">阴虚质:</Text>
                    {item.yin === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">阳虚质:</Text>
                    {item.yang === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">痰湿质:</Text>
                    {item.yan === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">湿热质:</Text>
                    {item.shi === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">血瘀质:</Text>
                    {item.xue === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">气郁质:</Text>
                    {item.yu === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                  <div className="flex justify-between items-center">
                    <Text size="small">特禀质:</Text>
                    {item.te === 1 ? (
                      <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
                    ) : (
                      <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
                    )}
                  </div>
                </div>
                
                <Divider style={{ margin: '12px 0' }} />
                
                {/* 操作按钮组 */}
                <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                  <Button 
                    type="primary" 
                    size="small"
                     onClick={()=>xian(item.id)}
                    icon={<ZoomOutOutlined />}
                    style={{ ...actionButtonStyle, backgroundColor: '#1890ff' }}
                  >
                    查看
                  </Button>
                 
                 
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      </Spin>
      
      {/* 卡片布局分页 */}
      {!loading && count > 0 && (
        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <Pagination
            current={currentPage}
            pageSize={constPageSize}
            total={count}
            showTotal={(total) => `共 ${total} 条`}
            showSizeChanger={false} // 固定每页2条，不允许修改
            showQuickJumper
            onChange={(page) => fetchUsers(page)}
          />
        </div>
      )}
    </div>
  );

  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      {/* 操作栏 */}
      <Flex justify="space-between" align="center" style={{ marginBottom: 20, flexWrap: 'wrap', gap: 10 }}>
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<FolderAddOutlined />}
            loading={loadings[1]}
            onClick={() => enterLoading(1)}
            style={{ padding: '6px 12px' }}
          >
            新增体测
          </Button>
          
          {/* 布局切换按钮组 */}
          <Space>
            <Button
              type={layoutMode === 'table' ? 'primary' : 'default'}
              size="small"
              icon={<TableOutlined />}
              onClick={() => setLayoutMode('table')}
            >
              表格
            </Button>
            <Button
              type={layoutMode === 'card' ? 'primary' : 'default'}
              size="small"
              icon={<BlockOutlined />}
              onClick={() => setLayoutMode('card')}
            >
              卡片
            </Button>
          </Space>
        </Space>
        
        <Space>
          <Input 
            value={inputvalue} 
            onChange={changeCount1} 
            size="small" 
            style={{ width: 200 }} 
            placeholder="档案号/姓名" 
            prefix={<UserOutlined />} 
          />
          <Button
            type="primary"
            size="small"
            icon={<SearchOutlined />}
            loading={loadings1[1]}
            onClick={() => enterLoading1(1)}
            style={yellowButtonStyle}
          >
            查询
          </Button>
        </Space>
      </Flex>

      {/* 模态框 */}
      <Modal
        title="添加用户"
        open={isModalOpen}
        onCancel={handleCancel}
        maskClosable={false}
        width={1000}
        footer={null}
      >
        <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '20px auto' }} />}>
          <AddUserForm 
            onSuccess={handleAddSuccess} 
                      onCancel={handleCancel}  
          />
        </Suspense>
      </Modal>

           <Modal
        title="查询"
        open={isModalOpen1}
        onCancel={handleCance2}
        maskClosable={false}
        width={1000}
        footer={null}
      >
        <Suspense fallback={<Spin size="large" style={{ display: 'block', margin: '20px auto' }} />}>
          <AddUserForm1 
            onSuccess={handleAddSuccess1} 
            onCancel={handleCance2} 
             value={pageValue} 
          />
        </Suspense>
      </Modal>

      {/* 布局内容区域 */}
      <div className="bg-white p-4 rounded-lg shadow-sm">
        {layoutMode === 'table' ? (
          <Table<IGanyut>
            loading={loading}
            dataSource={data}
            rowKey="id"
            scroll={{ x: 'max-content' }}
            rowSelection={rowSelection}
            pagination={{
              total: count,
              current: currentPage,
              pageSize: constPageSize, // 每页2条
              showTotal: (total) => `共 ${total} 条`,
              showSizeChanger: false, // 固定每页2条
              showQuickJumper: true,
              position: ['bottomCenter'],
              onChange: (page) => fetchUsers(page)
            }}
          >
            <Column title="档案号" dataIndex="fileNumber" key="userId" fixed='left' width={120} />
            <Column title="姓名" dataIndex="name" key="userName" fixed='left' width={80}/>
            <Column title="性别" dataIndex="sex" key="sex" fixed='left' width={60} />
            <Column 
              title="评估日期" 
              dataIndex="pdata" 
              key="birthday" 
              fixed='left' 
              width={120}
              render={(pdata) => pdata ? dayjs(pdata).format('YYYY-MM-DD') : '-'}
            />    
            <Column 
              title="气虚质" 
              dataIndex="qi"  
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="平和质" 
              dataIndex="pin" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="阴虚质" 
              dataIndex="yin" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="阳虚质" 
              dataIndex="yang" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="痰湿质" 
              dataIndex="yan" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="湿热质" 
              dataIndex="shi" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="血瘀质" 
              dataIndex="xue" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="气郁质" 
              dataIndex="yu" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            <Column 
              title="特禀质" 
              dataIndex="te" 
              render={(zzz) => zzz === 1 ? (
                <Tag icon={<FileAddOutlined />} color="#cd201f">是</Tag>
              ) : (
                <Tag icon={<FileProtectOutlined />} color="#55acee">否</Tag>
              )}
            />
            {/* 美化操作按钮 */}
            <Column
              title="操作"
              key="action"
              fixed='right'
              width={120}
              render={(_: any, record: IGanyut) => (
                <Space size="small">
                  <Button 
                    type="primary" 
                    size="small"
                    onClick={()=>xian(record.id)}
                    icon={<ZoomOutOutlined />}
                    style={{ ...actionButtonStyle, backgroundColor: '#1890ff' }}
                  >
                    查看
                  </Button>

                </Space>
              )}
            />
          </Table>
        ) : (
          renderCardLayout()
        )}
      </div>
    </div>
  );
}

export default Users;